/**
 * @file 用户信息
 * @date 2025/11/11 22:33:13
 * @author lyqjob@yeah.net
 */

import {  useState ,useEffect } from 'react';
import { Row, Col, Card, Upload, Image, Button, Flex, message, Descriptions, Spin ,Form ,Input,Space} from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';
import styles from './index.less'
// import { getBase64 } from '@/utils/utils';
import { adminApi } from '@/services/admin';
import SparkMD5 from 'spark-md5';
import ImgCrop from 'antd-img-crop';
import dayjs from '@/utils/dayjs.js';
import { useDispatch } from 'react-redux'
import { setuserinfo } from '@/store/reducers/global';

const UserInfo = () => {
    const dispatch = useDispatch();
    const [form] = Form.useForm();
    const [activeTabKey, setActiveTabKey] = useState('static');
    const [userInfo, setUserInfo] = useState();
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState();
    const [imageUrl, setImageUrl] = useState();
    const [loading, setLoading] = useState(false);
    const [hash, setHash] = useState('');
    const userinfo = useSelector(state => state.global.userInfo);

    useEffect(() => {
        getUserInfo();
    }, []);

    // 获取用户信息
    const getUserInfo = async () => {
        const [err,res] = await adminApi.getUserInfo(userinfo?.id);
        if(err) {
            // message.error('获取用户信息失败');
            // return;
        }
        if (res.code === 200) {
            setUserInfo(res.data);
            setImageUrl(res.data?.avatar_url);
            form.setFieldsValue(res.data);
        }
    }

    // tab列表
    const tabList = [
        {
            key: 'static',
            tab: '基本资料',
        },
        {
            key: 'dynamic',
            tab: '修改密码',
        },
    ];

    // tab切换
    const onTabChange = key => {
        setActiveTabKey(key);
        if(key === 'static'){
            form.setFieldsValue(userInfo);
        }
    };


    // 上传前校验
    const beforeUpload = file => {

        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只支持上传JPG/PNG格式的图片!');
            return false;
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片大小必须小于2MB!');
            return false;
        }

        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            const spark = new SparkMD5.ArrayBuffer();
            reader.readAsArrayBuffer(file);
            reader.onload = (e) => {
                spark.append(e.target.result);
                const hash = spark.end();
                file.hash = hash;
                setHash(hash)
                setTimeout(() => {
                    resolve(true);
                }, 0);
            };

            reader.onerror = () => {
                message.error('文件读取失败');
                reject();
            };
        });
    };

    // 预览图片
    const handlePreview = async (_file) => {
        setPreviewImage(userInfo?.avatar_url);
        setPreviewOpen(true);
    };

    // 自定义上传请求，包含hash值
    // const customRequest = ({ file, onSuccess, onError, onProgress }) => {
    //     const formData = new FormData();
    //     formData.append('avatar', file);
    //     formData.append('hash', file.hash); // 添加hash值到表单数据
    //     console.log('file', file);
    //     adminApi.uploadAvatar(formData, {
    //         onUploadProgress: (event) => {
    //             const percent = Math.round((event.loaded / event.total) * 100);
    //             onProgress({ percent });
    //         }
    //     },
    //         {
    //         headers: {
    //             'Hash': file.hash
    //         }
    //         }
    //     )
    //     .then(res => {
    //         console.log('上传成功响应:', res);
    //         onSuccess(res, file);
    //         message.success('头像上传成功');
    //         // 从响应中获取服务器返回的图片URL
    //         if (res.data && res.data.avatarUrl) {
    //             setImageUrl(`${location.origin}${res.data.avatarUrl}`);
    //         }
    //     })
    //     .catch(err => {
    //         console.error('上传失败:', err);
    //         onError(err);
    //         message.error('头像上传失败，请重试');
    //     });
    // };

    // 上传文件状态变化处理
    const handleChange = ({ file }) => {
        if (file.status === 'uploading') {
            setLoading(true);
            return;
        }

        if (file.status === 'done') {
            setLoading(false);
            if (file.response.code === 200) {
                message.success('头像上传成功');
                // 从响应中获取服务器返回的图片URL
                if (file.response.data && file.response.data.avatarUrl) {
                    setImageUrl(file.response.data.avatarUrl);
                    dispatch(setuserinfo({...userinfo,avatar:file.response.data.avatarUrl}))
                    
                    
                }
            } else {
                message.error('头像上传失败，请重试');
            }
            // 这里不再需要额外获取base64，因为已经从服务器获取了URL
        }

        if (file.status === 'error') {
            setLoading(false);
            message.error('上传失败');
        }
    };

    // 上传按钮
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </button>
    );


    // 基本资料表单
    const StaticInfo = () => {
        return (
            <>
                <Form.Item
                    label="用户名"
                    name="username"
                    rules={[{ required: true, message: '请输入用户名!' }]}
                    >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="姓名"
                    name="name"
                    rules={[{ required: true, message: '请输入姓名!' }]}
                    >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="手机号"
                    name="phone"
                    rules={[{ required: true, message: '请输入手机号!' }]}
                    >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[{ required: true, message: '请输入邮箱!' }]}
                    >
                    <Input />
                </Form.Item>

            </>
        )
    }

    // 修改密码表单
    const DynamicInfo = () => {
        return (
            <>
                <Form.Item
                    label="旧密码"
                    name="oldPassword"
                    rules={[{ required: true, message: '请输入旧密码!' }]}
                    >
                    <Input.Password />
                </Form.Item>
                <Form.Item
                    label="新密码"
                    name="newPassword"
                    extra="请输入6-16位字母、数字或符号,至少包含一个大写字母、小写字母、数字和符号"
                    rules={[
                        { required: true, message: '请输入新密码!' },
                        { min: 6, max: 16, message: '密码长度必须在6-16位之间' },
                        {
                            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{6,16}$/,
                            message: '密码必须包含至少一个大写字母、一个小写字母、一个数字和一个特殊字符'
                        }
                    ]}
                    >
                    <Input.Password />
                </Form.Item>
                <Form.Item
                    label="确认新密码"
                    name="confirmNewPassword"
                    rules={[{ required: true, message: '请确认新密码!' }]}
                    >
                    <Input.Password />
                </Form.Item>
            </>
        )
    }

    const contentList = {
        static: <StaticInfo />,
        dynamic: <DynamicInfo />,
    };

    const handleSubmit = async (values) => {
        if(activeTabKey === 'static'){
            values.id = userInfo?.id;
            const [err,res] = await adminApi.updateUserInfo(values)
            if(err){
                // message.error(err.message)
                return
            }

            if(res?.code === 200){
                getUserInfo()
                message.success('修改用户信息成功')
                return
            }
        }

        // 修改密码
        if(values?.newPassword !== values?.confirmNewPassword){
            message.error('新密码和确认新密码不一致')
            return
        }

        const [err,res] = await adminApi.updatePassword(values)
        if(err){
            // message.error(err.message)
            // return
        }
        if(res?.code === 200){
            form.resetFields()
            
            message.success('修改密码成功')
        }

    }

    return (
        <Spin spinning={loading}>
            <Row gutter={16} className={styles.container}>
                <Col span={10} >
                    <Card title="个人信息" variant="outlined" className={styles.staticinfo} extra={<Button onClick={handlePreview}>预览大图</Button>}>
                        <Flex gap="middle" justify="center">
                            
                                <ImgCrop rotationSlider>
                                    <Upload
                                        wrapperStyle={{ width: '120px', height: '120px', objectFit: 'cover' }}
                                        name="avatar"
                                        className="avatar-uploader"
                                        action={`${location.origin}/api/auth/upload-avatar`}
                                        headers={{
                                            Authorization: `Bearer ${localStorage.getItem('access_token')}`,
                                            Hash: hash
                                        }}
                                        listType="picture-circle"
                                        // fileList={fileList}
                                        showUploadList={false}
                                        beforeUpload={beforeUpload}
                                        // customRequest={customRequest}
                                        style={{ width: '120px', height: '120px', objectFit: 'cover', borderRadius: '50%', overflow: 'hidden' }}
                                        onPreview={handlePreview}
                                        onChange={handleChange}
                                        progress={{
                                            strokeColor: {
                                                '0%': '#108ee9',
                                                '100%': '#87d068',
                                            },
                                            strokeWidth: 3,
                                            format: percent => percent && `${Number.parseFloat(percent.toFixed(2))}%`,
                                        }}
                                    >
                                        {imageUrl ? (
                                            <img draggable={false} src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                                        ) : (
                                        uploadButton
                                        )}
                                    </Upload>
                                </ImgCrop>
                            {/* } */}
                        </Flex>
                        {
                            previewImage && 
                            <Image
                                width={200}
                                style={{ display: 'none' }}
                                src={previewImage}
                                preview={{
                                    visible:previewOpen,
                                    // scaleStep,
                                    src: previewImage,
                                    onVisibleChange: value => {
                                        setPreviewOpen(value);
                                    },
                                }}
                            />
                        }
                        <Descriptions column={1} bordered style={{ marginTop: 10 }} size='small'>
                            <Descriptions.Item label="用户名">{userInfo?.username}</Descriptions.Item>
                            <Descriptions.Item label="姓名">{userInfo?.name}</Descriptions.Item>
                            <Descriptions.Item label="性别">{userInfo?.gender === 1 ? '男' : userInfo?.gender === 2 ? '未知' : '女'}</Descriptions.Item>
                            <Descriptions.Item label="手机号">{userInfo?.phone}</Descriptions.Item>
                            <Descriptions.Item label="邮箱">{userInfo?.email}</Descriptions.Item>
                            <Descriptions.Item label="部门">{userInfo?.department_name}</Descriptions.Item>
                            {/* <Descriptions.Item label="角色"> <Tag color="green" key={0}>{userInfo?.roles[0]?.name || '无'}</Tag></Descriptions.Item> */}
                            <Descriptions.Item label="创建时间">{dayjs(userInfo?.created_at).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
                        </Descriptions>
                    </Card>
                </Col>
                <Col span={14}>
                    
                    <Card
                        style={{ width: '100%' }}
                        title="基本资料"
                        // extra={<a href="#">More</a>}
                        tabList={tabList}
                        activeTabKey={activeTabKey}
                        onTabChange={onTabChange}
                    >   <Form
                            form={form}
                            name="basic"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}
                            style={{ maxWidth: 600 }}
                            // initialValues={{ remember: true }}
                            onFinish={handleSubmit}
                            // onFinishFailed={onFinishFailed}
                            autoComplete="off"
                        >
                            {contentList[activeTabKey]}
                        </Form>
                        
                        <Space>
                            <Button type="primary" danger onClick={()=>form.resetFields()}>
                                重置
                            </Button>
                            <Button type="primary" htmlType="submit" onClick={()=>form.submit()}>
                                保存
                            </Button>

                        </Space>
                        
                    </Card>
                    
                </Col>
            </Row>
        </Spin>
    )
}

export default UserInfo